// 统一API响应格式接口

// 基础响应接口
export interface BaseResponse<T = any> {
  success: boolean;
  message: string;
  data?: T;
  error?: ErrorInfo;
  timestamp: string;
  requestId?: string;
}

// 成功响应接口
export interface SuccessResponse<T = any> extends BaseResponse<T> {
  success: true;
  data: T;
}

// 错误响应接口
export interface ErrorResponse extends BaseResponse {
  success: false;
  error: ErrorInfo;
}

// 错误信息接口
export interface ErrorInfo {
  code: string;
  message: string;
  details?: any;
  stack?: string;
  suggestions?: string[];
}

// 分页响应接口
export interface PaginatedResponse<T = any> extends SuccessResponse<T[]> {
  pagination: PaginationInfo;
}

// 分页信息接口
export interface PaginationInfo {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
  hasNext: boolean;
  hasPrev: boolean;
}

// 分页请求参数接口
export interface PaginationParams {
  page?: number;
  pageSize?: number;
  sortBy?: string;
  sortOrder?: 'asc' | 'desc';
}

// 排序参数接口
export interface SortParams {
  field: string;
  order: 'asc' | 'desc';
}

// 搜索参数接口
export interface SearchParams {
  keyword?: string;
  filters?: Record<string, any>;
  dateRange?: {
    start: string;
    end: string;
  };
}

// 批量操作响应接口
export interface BatchOperationResponse {
  success: boolean;
  total: number;
  successful: number;
  failed: number;
  errors: Array<{
    id: string;
    error: string;
  }>;
}

// 错误码枚举
export enum ErrorCode {
  // 通用错误
  UNKNOWN_ERROR = 'UNKNOWN_ERROR',
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  AUTHENTICATION_ERROR = 'AUTHENTICATION_ERROR',
  AUTHORIZATION_ERROR = 'AUTHORIZATION_ERROR',
  NOT_FOUND = 'NOT_FOUND',
  CONFLICT = 'CONFLICT',
  RATE_LIMIT_EXCEEDED = 'RATE_LIMIT_EXCEEDED',
  
  // 数据库相关错误
  DATABASE_CONNECTION_ERROR = 'DATABASE_CONNECTION_ERROR',
  DATABASE_QUERY_ERROR = 'DATABASE_QUERY_ERROR',
  DATABASE_CONSTRAINT_ERROR = 'DATABASE_CONSTRAINT_ERROR',
  DATABASE_TIMEOUT = 'DATABASE_TIMEOUT',
  
  // 脚本相关错误
  SCRIPT_NOT_FOUND = 'SCRIPT_NOT_FOUND',
  SCRIPT_SYNTAX_ERROR = 'SCRIPT_SYNTAX_ERROR',
  SCRIPT_EXECUTION_ERROR = 'SCRIPT_EXECUTION_ERROR',
  SCRIPT_PERMISSION_DENIED = 'SCRIPT_PERMISSION_DENIED',
  SCRIPT_VERSION_CONFLICT = 'SCRIPT_VERSION_CONFLICT',
  
  // 连接相关错误
  CONNECTION_NOT_FOUND = 'CONNECTION_NOT_FOUND',
  CONNECTION_TEST_FAILED = 'CONNECTION_TEST_FAILED',
  CONNECTION_TIMEOUT = 'CONNECTION_TIMEOUT',
  CONNECTION_AUTHENTICATION_FAILED = 'CONNECTION_AUTHENTICATION_FAILED',
  CONNECTION_POOL_EXHAUSTED = 'CONNECTION_POOL_EXHAUSTED',
  
  // 执行相关错误
  EXECUTION_NOT_FOUND = 'EXECUTION_NOT_FOUND',
  EXECUTION_ALREADY_RUNNING = 'EXECUTION_ALREADY_RUNNING',
  EXECUTION_CANCELLED = 'EXECUTION_CANCELLED',
  EXECUTION_TIMEOUT = 'EXECUTION_TIMEOUT',
  EXECUTION_QUEUE_FULL = 'EXECUTION_QUEUE_FULL',
  
  // 版本相关错误
  VERSION_NOT_FOUND = 'VERSION_NOT_FOUND',
  VERSION_CONFLICT = 'VERSION_CONFLICT',
  VERSION_ROLLBACK_FAILED = 'VERSION_ROLLBACK_FAILED',
  
  // 文件相关错误
  FILE_NOT_FOUND = 'FILE_NOT_FOUND',
  FILE_UPLOAD_ERROR = 'FILE_UPLOAD_ERROR',
  FILE_SIZE_EXCEEDED = 'FILE_SIZE_EXCEEDED',
  FILE_TYPE_NOT_SUPPORTED = 'FILE_TYPE_NOT_SUPPORTED',
  
  // 缓存相关错误
  CACHE_CONNECTION_ERROR = 'CACHE_CONNECTION_ERROR',
  CACHE_OPERATION_ERROR = 'CACHE_OPERATION_ERROR',
  
  // 业务逻辑错误
  FOLDER_NOT_EMPTY = 'FOLDER_NOT_EMPTY',
  CIRCULAR_DEPENDENCY = 'CIRCULAR_DEPENDENCY',
  RESOURCE_LOCKED = 'RESOURCE_LOCKED',
  OPERATION_NOT_ALLOWED = 'OPERATION_NOT_ALLOWED'
}

// 错误消息映射
export const ErrorMessages: Record<ErrorCode, string> = {
  [ErrorCode.UNKNOWN_ERROR]: '未知错误',
  [ErrorCode.VALIDATION_ERROR]: '数据验证失败',
  [ErrorCode.AUTHENTICATION_ERROR]: '身份验证失败',
  [ErrorCode.AUTHORIZATION_ERROR]: '权限不足',
  [ErrorCode.NOT_FOUND]: '资源不存在',
  [ErrorCode.CONFLICT]: '资源冲突',
  [ErrorCode.RATE_LIMIT_EXCEEDED]: '请求频率超限',
  
  [ErrorCode.DATABASE_CONNECTION_ERROR]: '数据库连接失败',
  [ErrorCode.DATABASE_QUERY_ERROR]: '数据库查询错误',
  [ErrorCode.DATABASE_CONSTRAINT_ERROR]: '数据库约束违反',
  [ErrorCode.DATABASE_TIMEOUT]: '数据库操作超时',
  
  [ErrorCode.SCRIPT_NOT_FOUND]: '脚本不存在',
  [ErrorCode.SCRIPT_SYNTAX_ERROR]: 'SQL语法错误',
  [ErrorCode.SCRIPT_EXECUTION_ERROR]: '脚本执行失败',
  [ErrorCode.SCRIPT_PERMISSION_DENIED]: '脚本访问权限不足',
  [ErrorCode.SCRIPT_VERSION_CONFLICT]: '脚本版本冲突',
  
  [ErrorCode.CONNECTION_NOT_FOUND]: '数据库连接配置不存在',
  [ErrorCode.CONNECTION_TEST_FAILED]: '数据库连接测试失败',
  [ErrorCode.CONNECTION_TIMEOUT]: '数据库连接超时',
  [ErrorCode.CONNECTION_AUTHENTICATION_FAILED]: '数据库认证失败',
  [ErrorCode.CONNECTION_POOL_EXHAUSTED]: '数据库连接池已满',
  
  [ErrorCode.EXECUTION_NOT_FOUND]: '执行记录不存在',
  [ErrorCode.EXECUTION_ALREADY_RUNNING]: '脚本正在执行中',
  [ErrorCode.EXECUTION_CANCELLED]: '执行已取消',
  [ErrorCode.EXECUTION_TIMEOUT]: '执行超时',
  [ErrorCode.EXECUTION_QUEUE_FULL]: '执行队列已满',
  
  [ErrorCode.VERSION_NOT_FOUND]: '版本不存在',
  [ErrorCode.VERSION_CONFLICT]: '版本冲突',
  [ErrorCode.VERSION_ROLLBACK_FAILED]: '版本回滚失败',
  
  [ErrorCode.FILE_NOT_FOUND]: '文件不存在',
  [ErrorCode.FILE_UPLOAD_ERROR]: '文件上传失败',
  [ErrorCode.FILE_SIZE_EXCEEDED]: '文件大小超限',
  [ErrorCode.FILE_TYPE_NOT_SUPPORTED]: '不支持的文件类型',
  
  [ErrorCode.CACHE_CONNECTION_ERROR]: '缓存连接失败',
  [ErrorCode.CACHE_OPERATION_ERROR]: '缓存操作失败',
  
  [ErrorCode.FOLDER_NOT_EMPTY]: '文件夹不为空',
  [ErrorCode.CIRCULAR_DEPENDENCY]: '存在循环依赖',
  [ErrorCode.RESOURCE_LOCKED]: '资源被锁定',
  [ErrorCode.OPERATION_NOT_ALLOWED]: '操作不被允许'
};

// HTTP状态码映射
export const HttpStatusMap: Record<ErrorCode, number> = {
  [ErrorCode.UNKNOWN_ERROR]: 500,
  [ErrorCode.VALIDATION_ERROR]: 400,
  [ErrorCode.AUTHENTICATION_ERROR]: 401,
  [ErrorCode.AUTHORIZATION_ERROR]: 403,
  [ErrorCode.NOT_FOUND]: 404,
  [ErrorCode.CONFLICT]: 409,
  [ErrorCode.RATE_LIMIT_EXCEEDED]: 429,
  
  [ErrorCode.DATABASE_CONNECTION_ERROR]: 503,
  [ErrorCode.DATABASE_QUERY_ERROR]: 500,
  [ErrorCode.DATABASE_CONSTRAINT_ERROR]: 400,
  [ErrorCode.DATABASE_TIMEOUT]: 504,
  
  [ErrorCode.SCRIPT_NOT_FOUND]: 404,
  [ErrorCode.SCRIPT_SYNTAX_ERROR]: 400,
  [ErrorCode.SCRIPT_EXECUTION_ERROR]: 500,
  [ErrorCode.SCRIPT_PERMISSION_DENIED]: 403,
  [ErrorCode.SCRIPT_VERSION_CONFLICT]: 409,
  
  [ErrorCode.CONNECTION_NOT_FOUND]: 404,
  [ErrorCode.CONNECTION_TEST_FAILED]: 400,
  [ErrorCode.CONNECTION_TIMEOUT]: 504,
  [ErrorCode.CONNECTION_AUTHENTICATION_FAILED]: 401,
  [ErrorCode.CONNECTION_POOL_EXHAUSTED]: 503,
  
  [ErrorCode.EXECUTION_NOT_FOUND]: 404,
  [ErrorCode.EXECUTION_ALREADY_RUNNING]: 409,
  [ErrorCode.EXECUTION_CANCELLED]: 200,
  [ErrorCode.EXECUTION_TIMEOUT]: 504,
  [ErrorCode.EXECUTION_QUEUE_FULL]: 503,
  
  [ErrorCode.VERSION_NOT_FOUND]: 404,
  [ErrorCode.VERSION_CONFLICT]: 409,
  [ErrorCode.VERSION_ROLLBACK_FAILED]: 500,
  
  [ErrorCode.FILE_NOT_FOUND]: 404,
  [ErrorCode.FILE_UPLOAD_ERROR]: 500,
  [ErrorCode.FILE_SIZE_EXCEEDED]: 413,
  [ErrorCode.FILE_TYPE_NOT_SUPPORTED]: 415,
  
  [ErrorCode.CACHE_CONNECTION_ERROR]: 503,
  [ErrorCode.CACHE_OPERATION_ERROR]: 500,
  
  [ErrorCode.FOLDER_NOT_EMPTY]: 400,
  [ErrorCode.CIRCULAR_DEPENDENCY]: 400,
  [ErrorCode.RESOURCE_LOCKED]: 423,
  [ErrorCode.OPERATION_NOT_ALLOWED]: 405
};

// 响应构建器类
export class ResponseBuilder {
  static success<T>(data: T, message: string = '操作成功'): SuccessResponse<T> {
    return {
      success: true,
      message,
      data,
      timestamp: new Date().toISOString()
    };
  }

  static error(
    code: ErrorCode,
    message?: string,
    details?: any,
    suggestions?: string[]
  ): ErrorResponse {
    return {
      success: false,
      message: message || ErrorMessages[code],
      error: {
        code,
        message: message || ErrorMessages[code],
        details,
        ...(suggestions && { suggestions })
      },
      timestamp: new Date().toISOString()
    };
  }

  static paginated<T>(
    data: T[],
    pagination: PaginationInfo,
    message: string = '查询成功'
  ): PaginatedResponse<T> {
    return {
      success: true,
      message,
      data,
      pagination,
      timestamp: new Date().toISOString()
    };
  }

  static batchOperation(
    total: number,
    successful: number,
    failed: number,
    errors: Array<{ id: string; error: string }> = []
  ): BatchOperationResponse {
    return {
      success: failed === 0,
      total,
      successful,
      failed,
      errors
    };
  }
}

// 分页工具函数
export class PaginationUtils {
  static calculatePagination(
    page: number,
    pageSize: number,
    total: number
  ): PaginationInfo {
    const totalPages = Math.ceil(total / pageSize);
    
    return {
      page,
      pageSize,
      total,
      totalPages,
      hasNext: page < totalPages,
      hasPrev: page > 1
    };
  }

  static getOffset(page: number, pageSize: number): number {
    return (page - 1) * pageSize;
  }

  static validatePaginationParams(params: PaginationParams): {
    page: number;
    pageSize: number;
    sortBy?: string;
    sortOrder: 'asc' | 'desc';
  } {
    const page = Math.max(1, params.page || 1);
    const pageSize = Math.min(100, Math.max(1, params.pageSize || 20));
    const sortOrder = params.sortOrder === 'desc' ? 'desc' : 'asc';
    
    const result: {
      page: number;
      pageSize: number;
      sortBy?: string;
      sortOrder: 'asc' | 'desc';
    } = {
      page,
      pageSize,
      sortOrder
    };

    if (params.sortBy) {
      result.sortBy = params.sortBy;
    }

    return result;
  }
}

// 请求验证相关类型
export interface ValidationResult {
  isValid: boolean;
  errors: ValidationError[];
}

export interface ValidationError {
  field: string;
  message: string;
  value?: any;
}

// API请求上下文接口
export interface RequestContext {
  requestId: string;
  userId?: string;
  userRole?: string;
  clientIp: string;
  userAgent: string;
  timestamp: Date;
}

// 操作日志接口
export interface OperationLog {
  id: string;
  userId?: string;
  operation: string;
  resource: string;
  resourceId?: string;
  details?: any;
  timestamp: Date;
  clientIp: string;
  userAgent: string;
}

// 性能监控接口
export interface PerformanceMetric {
  operation: string;
  duration: number;
  timestamp: Date;
  details?: any;
}

// 健康检查响应接口
export interface HealthCheckResponse {
  status: 'healthy' | 'unhealthy' | 'degraded';
  timestamp: string;
  uptime: number;
  version: string;
  services: {
    database: ServiceStatus;
    redis: ServiceStatus;
    doris?: ServiceStatus;
  };
}

export interface ServiceStatus {
  status: 'up' | 'down' | 'degraded';
  responseTime?: number;
  error?: string;
  lastCheck: string;
}